﻿using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Safebrowsing
{
    /// <summary>
    /// Response containing full-length hashes.
    /// More info here: http://code.google.com/apis/safebrowsing/developers_guide_v2.html#HTTPResponseForHashes
    /// </summary>
    public class HashResponse
    {
        /// <summary>
        /// Creates an instance of the HashResponse
        /// </summary>
        /// <param name="data"></param>
        public HashResponse(byte[] data)
        {
            HashResponseEntries = new List<HashResponseEntry>();

            if (data.Length > 0)
            {
                using (Stream stream = new MemoryStream(data) { Position = 0 })
                {
                    string line = Utils.ReadLine(stream);
                    while (!string.IsNullOrEmpty(line))
                    {
                        string[] parts = line.Split(':');
                        if (parts.Length == 3)
                        {
                            string listName = parts[0];
                            int addChunkNumber = Utils.ToInt(parts[1]);
                            int hashDataLength = Utils.ToInt(parts[2]);
                            if (addChunkNumber >= 0 && hashDataLength >= 0)
                            {
                                byte[] hashdata = Utils.Read(stream, hashDataLength);
                                SafebrowsingList list = SafebrowsingList.GetListByName(listName);
                                if (list != null)
                                {
                                    // Adding this entry only if this safebrowsing list is registered
                                    var entry = new HashResponseEntry(list, addChunkNumber, hashdata);
                                    HashResponseEntries.Add(entry);
                                }
                            }
                        }

                        line = Utils.ReadLine(stream);
                    }
                }                
            }
        }

        public List<HashResponseEntry> HashResponseEntries { get; private set; }

        public override string ToString()
        {
            var sb = new StringBuilder();

            if (HashResponseEntries.Count == 0) sb.Append("Empty response");

            foreach (HashResponseEntry entry in HashResponseEntries)
            {
                sb.AppendLine(entry.ToString());
            }

            return sb.ToString();
        }
    }
}
